<template>
    <div>
      <el-dialog v-model="dialogVisible" title="Tips" width="50%" :before-close="handleClose">
        <el-form :model="form">
          <el-form-item>
            <Editor v-model="form.content" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="dialogVisible = false">Confirm</el-button>
          </span>
        </template>
      </el-dialog>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <i class="el-icon-lx-cascades"></i>
            门票信息
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div class="handle-box">
          <el-input v-model="query.ticketName" placeholder="门票名" class="handle-input mr10"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
        <el-table
          :data="tableData"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
          >
          <el-table-column prop="ticketId" label="门票ID" width="55" align="center"></el-table-column>
          <el-table-column prop="ticketName" label="门票名称" width="80"></el-table-column>
          <el-table-column prop="price" label="票价"></el-table-column>
          <el-table-column prop="availabilityDate" label="可用日期">
            <template v-slot:default="scope">
              {{ formatDateToChineseDate(scope.row.availabilityDate) }}
            </template>
          </el-table-column>

          <el-table-column prop="quantityAvailable" label="票数"></el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm title="确定要删除该门票" confirm-button-text="确定" cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
          </el-table-column>
        </el-table>
         <div class="pagination">
        <el-pagination  :currentPage="query.currentPage" :page-size="query.pageSize"
          layout="prev, pager, next, jumper" :total="totalCount" @current-change="handleCurrentChange" ></el-pagination>
      </div>
      </div>
      <el-dialog v-model="centerDialogVisible" title="门票编辑" width="40%">
      <div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
          <el-form-item label="门票名" prop="ticketName">
            <el-input v-model="ruleForm.ticketName" />
          </el-form-item>
          <el-form-item label="票价" prop="price">
            <el-input v-model="ruleForm.price" type="number" step="0.01" />
          </el-form-item>
          <el-form-item label="可用日期" prop="availabilityDate">
            <el-input v-model="ruleForm.availabilityDate"  type="date"/>
          </el-form-item>
          <el-form-item label="票数" prop="quantityAvailable">
            <el-input v-model="ruleForm.quantityAvailable" type="number"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">更新</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
          <el-button @click="centerDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    </div>
  </template>
  <script>
  import { ref, reactive } from "vue";
  import { ElMessageBox } from "element-plus";
  import request from "../../utils/request";
  import Editor from "@/components/Editor.vue";
  import { ElNotification } from "element-plus";

  export default {
    components: {
      Editor,
    },
    setup() {
      function formatDateToChineseDate(dateStr) {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}年${month}月${day}日`;
}

      
      const dialogVisible = ref(false);
      const form = reactive({
        content: "",
      });
      const ruleFormRef = ref();
    const centerDialogVisible = ref(false);
      const query = reactive({
    ticketName: "",
    currentPage: 1,
    pageSize: 5,
  });
  
      // 查询操作
      const handleSearch = () => {
        getData();
      };
      // 分页导航
  
  const handleCurrentChange = (val) => {
      query.currentPage = val;
      getData();
     

    };
      // 删除操作
      const handleDelete = (index, row) => {
        request
          .request({
            url: "/ticket/delete",
            method: "get",
            params: {
              ticketId: row.ticketId,
              
            },
          })
            .then((res) => {
                if (res.data.msg == "success") {
                    getData();
                    ElNotification({
                      title: "删除成功",
                      message: "成功删除用户信息",
                    });
                  } else {
                    ElNotification({
                      title: "删除失败",
                      message: "请联系管理员检查失败原因",
                    });
                  }
                })
                .catch((e) => {
                  ElNotification({
                    title: "删除失败",
                    message: "请联系管理员检查失败原因",
                  });
                });};
const submitForm = async (formEl) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          // console.log("提交更新", fields);
          request
            .request({
              url: "/ticket/update",
              method: "post",
              data: {
                ticketId: ruleForm.ticketId,
                ticketName: ruleForm.ticketName,
                price: ruleForm.price,
                availabilityDate: ruleForm.availabilityDate,
                quantityAvailable: ruleForm.quantityAvailable,
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: "更新成功",
                  message: "成功更新用户信息",
                })
                getData();
              } else {
                ElNotification({
                  title: "更新失败",
                  message: "请联系管理员检查失败原因",
                });
              }
            })
            .catch((e) => {
              ElNotification({
                title: "更新失败",
                message: "请联系管理员检查失败原因",
              });
            });
        } else {
          ElNotification({
            title: "校验失败",
            message: "请重新填写信息",
          });
        }
      });
    };
    const ruleForm = reactive({
    ticketId: "",
    ticketName: "",
    price: "",
    availabilityDate: "",
    quantityAvailable: "",
  });
    const rules = reactive({
      ticketname: [
          {
            message: "请输入门票名",
            trigger: "blur",
            required: true,
          },
        ],
        price: [
        {
            required: true,
            message: "请输入价格",
            trigger: "blur",
        },
        {
            validator: (rule, value, callback) => {
            const priceRegex = /^\d+(\.\d{1,2})?$/; 
            if (!priceRegex.test(value)) {
                callback(new Error("最多两位小数"));
            } else {
                callback(); // 验证通过
            }
            },
            trigger: "blur",
        },
        ],

        availabilityDate: [
          {
            required: true,
            message: "请输入可用日期",
            trigger: "blur",
          },
        ],
        quantityAvailable: [
          {
            required: true,
            message: "请输入票数",
            trigger: "blur",
          },
        ],
    
    });
    const resetForm = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    
      //修改操作
// 修改操作
const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.ticketId = row.ticketId;
  ruleForm.ticketName = row.ticketName;
  ruleForm.price = row.price;
  ruleForm.availabilityDate = new Date(row.availabilityDate).toISOString().split('T')[0];
  ruleForm.quantityAvailable = row.quantityAvailable;
};


      const handleClose = (done) => {
        ElMessageBox.confirm("Are you sure to close this dialog?")
          .then(() => {
            done();
          })
          .catch(() => {
            // catch error
          });
      };
      const tableData = ref([]);
      const totalCount = ref(0);
      // 获取表格数据
      const getData = () => {
        request.request({
          url: "/ticket/getAllTicket",
          params: {
            ticketName: query.ticketName,
            currentPage: query.currentPage,
            pageSize: query.pageSize,
          },
          method: "get",
        })
          .then((res) => {
            console.log(res.data.data);
            tableData.value = res.data.data.rows;
            totalCount.value = res.data.data.count;
            console.log(totalCount.value); // 获取 totalCount 的实际值
          
          })
          .catch((e) => {
            console.log(e);
          });
      };
      getData();
  
      
  return {
    query,
    submitForm,
    rules,
    ruleForm,
    ruleFormRef,
    centerDialogVisible,
    tableData,
    dialogVisible,
    form,
    resetForm,
    handleCurrentChange,
    getData,
    handleSearch,
    totalCount,
    handleDelete,
    handleEdit,
    handleClose,
    formatDateToChineseDate, 
  };
    },
  };
  </script>
  <style lang="scss" scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  
  .handle-select {
    width: 120px;
  }
  
  .handle-input {
    width: 300px;
    display: inline-block;
  }
  
  .table {
    width: 100%;
    font-size: 14px;
  }
  
  .red {
    color: #ff0000;
  }
  
  .mr10 {
    margin-right: 10px;
  }
  
  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
  
  .dialog-footer button:first-child {
    margin-right: 10px;
  }
  </style>